package org.easy4j.framework.core.util;

import org.easy4j.framework.core.util.base.Strings;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: liuyong
 * @since 1.0
 */
public class UrlBuilder {
    
    private String baseUrl = "" ;

    private String path ;

    private Map<String,Object> parameters ;

    public UrlBuilder() {

    }

    public UrlBuilder(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void setBaseUrl(String baseUrl){
        this.baseUrl = baseUrl ;
    }

    public String getUrl(String path){
        return this.baseUrl + path ;
    }

    public UrlBuilder newBuilder(String path){

        UrlBuilder newInstance = new UrlBuilder(this.baseUrl);
        newInstance.setPath(path);

        return newInstance ;

    }

    public UrlBuilder add(String name ,Object value) {

        if(parameters == null ) {
            parameters = new HashMap<String, Object>();
        }

        parameters.put(name , value) ;
        return this ;

    }

    public String toString(){

        StringBuilder builder = new StringBuilder(baseUrl) ;
        if(Strings.isNotBlank(path))
            builder.append(path);


        if(parameters == null || parameters.isEmpty()) {
            return  baseUrl.toString() ;
        }

        builder.append('?');

        for(Map.Entry<String,Object> entry : parameters.entrySet()) {
            builder.append(entry.getKey()).append("=").append(entry.getValue()).append('&');
        }

        builder.deleteCharAt(builder.length() -1);
        return builder.toString() ;
    }

    public void setPath(String path) {
        this.path = path;
    }


}
